package zhang.lao.service.sms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import zhang.lao.build.mybatis.jdbc.auto.dao.PhoneCodeMapper;
import zhang.lao.build.mybatis.jdbc.auto.model.PhoneCode;
import zhang.lao.build.mybatis.jdbc.auto.model.PhoneCodeExample;
import zhang.lao.build.tool.UUIDTool;
import zhang.lao.service.sms.exception.SmsRunTimeException;

import javax.annotation.Resource;
import java.util.Date;
import javax.annotation.Resource;
import java.util.Date;

@Service("SmsServiceImp")
public class SmsServiceImp implements SmsService {
        private static  final Logger logger = LoggerFactory.getLogger(SmsServiceImp.class);
    @Resource
    private SendTemplateSMS sendTemplateSMS;

    @Resource
    private PhoneCodeMapper phoneCodeMapper;
    /**
     * 获取验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public String getValidateCode(String phoneNumber){
        String number="";
        try{
            number=sendTemplateSMS.sendSms(phoneNumber);
            Date createTime=new Date();
            PhoneCode phone_code=new PhoneCode();
            phone_code.setId(UUIDTool.getUUID());
            phone_code.setCode(number);
            phone_code.setPhone(phoneNumber);
            phone_code.setCreateTime(createTime);
            phone_code.setExpiresTime(new Date(createTime.getTime()+Integer.parseInt(SendTemplateSMS.failureTime)*60000));
            phoneCodeMapper.insertSelective(phone_code);
            return number;
        }catch(SmsRunTimeException e){
            logger.error(e.getMsg(),e);
            throw new SmsRunTimeException("-1",e.getMessage());
        }

    }

    /**
     * 验证验证码是否可用
     */
    @Override
    public boolean validateCode(String phoneNumber, String code) {
        PhoneCodeExample phoneCodeExample = new PhoneCodeExample();
        phoneCodeExample.createCriteria().andPhoneEqualTo(phoneNumber).andCodeEqualTo(code).andExpiresTimeGreaterThan(new Date());
        return phoneCodeMapper.countByExample(phoneCodeExample)>0;
    }


}
